package create_mutex

import (
	"fmt"
	"syscall"
	"unsafe"
)

var (
	kernel32         = syscall.NewLazyDLL("kernel32.dll")
	procCreateMutex  = kernel32.NewProc("CreateMutexW")
	procReleaseMutex = kernel32.NewProc("ReleaseMutex")
	procGetLastError = kernel32.NewProc("GetLastError")
)

func createMutex(name string) (syscall.Handle, error) {
	namePtr, err := syscall.UTF16PtrFromString(name)
	if err != nil {
		return 0, err
	}

	handle, _, err := procCreateMutex.Call(0, 0, uintptr(unsafe.Pointer(namePtr)))
	if handle == 0 {
		return 0, err
	}
	return syscall.Handle(handle), nil
}

func releaseMutex(handle syscall.Handle) error {
	_, _, err := procReleaseMutex.Call(uintptr(handle))
	if err != nil && err.Error() != "The operation completed successfully." {
		return err
	}
	return nil
}

func CreatMutex() {
	mutexName := "Global\\MyUniqueMutexName"

	mutexHandle, err := createMutex(mutexName)
	if err != nil {
		fmt.Println("Failed to create mutex:", err)
		return
	}
	defer releaseMutex(mutexHandle)

	if syscall.GetLastError() == syscall.ERROR_ALREADY_EXISTS {
		fmt.Println("Another instance is already running.")
		return
	}

	fmt.Println("Application is running. Press Ctrl+C to exit.")

}
